package cn.hfatec.shms.web.yk.ykHsb.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.web.yk.ykHsb.model.YkHsb;
import cn.hfatec.shms.web.yk.ykHsb.model.YkHsbParams;
import cn.hfatec.shms.web.yk.ykHsb.service.YkHsbService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/yk/ykHsb")
public class YkHsbAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "YkHsbService")
    private YkHsbService ykHsbService;


    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(YkHsbParams ykHsbParams, Page page, Model model) {

        Table table = ykHsbService.queryYkHsbTable(ykHsbParams, page);
        YkHsb ykHj = ykHsbService.getYkHj(ykHsbParams);
        model.addAttribute("ykHsbsTable", table);
        model.addAttribute("ykHj", ykHj);
        model.addAttribute("ykHsbParams", ykHsbParams);
        return "/yk/ykHsb/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(YkHsbParams ykHsbParams, Page page, Model model) {
        try {
            list(ykHsbParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykHsb/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Model model) {
        try {
            YkHsb ykHsb = new YkHsb();
            model.addAttribute("ykHsb", ykHsb);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykHsb/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            YkHsb ykHsb = ykHsbService.getYkHsb(id);
            model.addAttribute("ykHsb", ykHsb);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/yk/ykHsb/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteYkHsb(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            ykHsbService.deleteYkHsbBatch(idList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveYkHsb(@Valid YkHsb ykHsb, BindingResult result) {

        try {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            ykHsbService.saveYkHsb(ykHsb);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据YkHsb保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }


    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goCheck")
    @ResponseBody
    public String goCheck(String hsTime, String hsEnd) {
        try {

            if (hsTime.length() == 0) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "核算开始时间不能为空").toString();
            }
            if (hsEnd.length() == 0) {
                hsEnd = hsTime;
            }
            long a = dataZ(hsTime, hsEnd) + 1;
            if (a < 0 || a > 15) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "核算时间范围大于15或者小于0").toString();
            }
            List<YkHsb> ykHsb = ykHsbService.selectYkhsb(hsTime, hsEnd);
            if (ykHsb != null && !ykHsb.isEmpty()) {
                String chect = "";
                for (YkHsb ykSelect : ykHsb) {
                    chect = ykSelect.getSpareA() + ' ' + ykSelect.getUserName() + ' ' + ';' + chect;
                }
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, chect + "未挂接部门，请检查！").toString();

            }
            ykHsbService.deleteYkHsb(hsTime, hsEnd);
            List<YkHsb> ykTj = ykHsbService.getYkTj(hsTime, hsEnd);
            if (ykTj != null && ykTj.size() > 0) {
                ykHsbService.saveYkHsbList(ykTj);
            }
            for (YkHsb ykHsbTj : ykTj) {//其内部实质上还是调用了迭代器遍历方式，这种循环方式还有其他限制，不建议使用。
                ykHsbService.updateYkTj(ykHsbTj.getSpareA());
            }
            List<YkHsb> ykJKgl = ykHsbService.getYkJkgl(hsTime, hsEnd);
            if (ykJKgl != null && ykJKgl.size() > 0) {
                ykHsbService.saveYkHsbList(ykJKgl);
            }
          /*  for (YkHsb ykHsbJkgl : ykJKgl) {//其内部实质上还是调用了迭代器遍历方式，这种循环方式还有其他限制，不建议使用。
                ykHsbService.saveYkHsb(ykHsbJkgl);
            }*/
            List<YkHsb> ykVip = ykHsbService.getYkVip(hsTime, hsEnd);
           /* for (YkHsb ykHsbVip : ykVip) {//其内部实质上还是调用了迭代器遍历方式，这种循环方式还有其他限制，不建议使用。
                ykHsbService.saveYkHsb(ykHsbVip);
            }*/
            if (ykVip != null && ykVip.size() > 0) {
                ykHsbService.saveYkHsbList(ykVip);
            }
            List<YkHsb> ykVipYj = ykHsbService.getYkHsbVipYj(hsTime, hsEnd);
           /* for (YkHsb ykHsbVip : ykVip) {//其内部实质上还是调用了迭代器遍历方式，这种循环方式还有其他限制，不建议使用。
                ykHsbService.saveYkHsb(ykHsbVip);
            }*/
            if (ykVipYj != null && ykVipYj.size() > 0) {
                ykHsbService.saveYkHsbList(ykVipYj);
            }
            if (ykTj != null) {
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", ykTj).toString();
            } else {
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", new YkHsb()).toString();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    private long dataZ(String hsTime, String hsEnd) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date hsDate = formatter.parse(hsTime);
        Date EndDate = formatter.parse(hsEnd);
        long day = (EndDate.getTime() - hsDate.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }

    /**
     * 导出excel
     */
    @RequestMapping("/export")
    @ResponseBody
    public String export(YkHsbParams ykHsbParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            ykHsbService.exportExcel(ykHsbParams, request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
}
